Anonymous Function

A standard function has a name, a list of parameters, a return type, and a body. If you do not give a name to a function, it is an anonymous function. An anonymus function provides a light function definition and is called as function literal in scala.
Syntax:
(argument1:Type,argument2:Type,.................) => body
object demo {
def main(args: Array[String]) {
val mul=(z:Int, y:Int)=> z*y
println(mul(2,3))
val mul1=(_:Int)*(_:Int)
println(mul1(5,2))
}
}
In the above first syntax, => is known as a transformer. The transformer is used to transform the parameter-list of the left-hand side of the symbol into a new result using the expression present on the right-hand side. In the above second syntax, _ character is known as a wildcard is a shorthand way to represent a parameter who appears only once in the anonymous function.

Anonymus functions with parameters
object demo {
def main(args: Array[String])
{
var function1 = (str1:String, str2:String) => str1 + str2
var function2 = (_:String) + (_:String)
println(function1("Scala ", " Python"))
println(function2("Python ", " Scala"))
}

object demo{
def main(args: Array[String])
{
val x = List.range(1, 10)
val evens = x.filter((i: Int) => i % 2 == 0)
println(evens)
val odds = x.filter((i: Int) => i % 2 != 0)
val odds1 = x.filter(_ % 2 != 0)
println(odds)
println(odds1)
}
}

Anonymus functions with out parameters
We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function.
// Scala program to illustrate anonymous method 
object demo
{
def main(args: Array[String])
{
// Creating anonymous functions
// without parameter
var myfun1 = () => {"Welcome to GeeksforGeeks...!!"}
println(myfun1())
// A function which contain anonymous
// function as a parameter
def myfunction(fun:(String, String)=> String) =
{
fun("Dog", "Cat")
}
// Explicit type declaration of anonymous
// function in another function
val f1 = myfunction((str1: String,
str2: String) => str1 + str2)
// Shorthand declaration using wildcard
val f2 = myfunction(_ + _)
println(f1)
println(f2)
}
}
                               
What is the purpose of an anonymous function?
Why would you want to create an anonymous function? The answer is simple. There might be scenarios where you want to create an inline function for a one-time usage. Giving a name to a function does not make any sense if you do not want to use it anywhere else. In those scenarios, creating an anonymous function is quite convenient. Let me show you an example. You have already seen the below example earlier.                            
                         
 
def getOps(c:Int) = {
        def doubler(x:Int) =  x * 2
        def tripler(x:Int) =  x * 3
        if(c > 0) 
            doubler _
        else
            tripler _
        } 
def getOps2(c:Int) = {
        if(c > 0)   (i:Int) => i * 2
        else    (i:Int) => i * 3
        }   
                
In the above code, we create two local functions and then return them later. The only purpose of creating those local functions is to return them. We can do the same thing using anonymous functions.          

The above code is much precise, straightforward and clean. Instead of defining two local functions and then returning them later, I simply use anonymous function, right at the place where it is needed. This kind of code is more convenient to write and easy to understand. In this example, both the anonymous functions have same input parameter list. So, we can apply another shortcut and move the input parameter list outside the body.
                                     
    def getOps2(c:Int) = (i:Int) => {
        if(c > 0)    i * 2
        else  i * 3
        }                 
                                 
You may have several such scenarios where you just want to create a function and use it right there. Anonymous functions are there to allow you to do that.

No comments:

Post a Comment